#include<stdlib.h>
#include<string.h>

/*
  This function takes a string 'str' and parses this string in various sub-strings depending on the seperation char 'c',
  'start', and 'end'. The sub-strings are returned.

  Example:

     char **s; short n;

     s = parse_int("  abababa   hshshshshs    jkjkjkjk uyuyuyuy ", ' ', 2, 6, &n);

   It will return:
        s[0] = "hshshshshs",
        s[1] = "jkjkjkjk",
        s[2] = "uyuyuyuy",
        s[3], s[4] and s[5]: doesn't exist;
        n = 3;
*/

extern char **parse_str(const char *str, char c, unsigned short start, unsigned short end, unsigned short *nsubs)
{
 int i, j, sstrlen, l, flag, sstrcnt, n;
 char **s;
 struct span {int start, sstrlen;} *sstr; /* sub-string */


 if(start > end) return (char **)0;

 n = end - start + 1;

 sstr = (struct span *)malloc(n*sizeof(struct span));

 l = strlen(str);

 for(sstrcnt = flag = i = j = sstrlen = 0; i < l; i++)
    {
     if(str[i] != c)
        {
         if(flag == 0) sstrcnt++;

      /* This records position of 1st char of j-th substring in the source string "str". */
         if((sstrcnt >= start)&&(sstrcnt <= end)) if(sstrlen++ == 0) sstr[j].start = i;

         flag = 1; /* Flag indicating that the a new substring is encountered. */
        }

    if(flag == 1) if((str[i] == c)||(i == l-1))
       {
        if((sstrcnt >= start)&&(sstrcnt <= end))
           {
            sstr[j++].sstrlen = sstrlen;
            if(j == n) break;
            sstrlen = 0;
           }
        flag = 0;
       }
   }

 s = (char **)malloc(sizeof(void *)*j); /* j = number of sub-strings satisfying the input criterion. */
//printf("------j = %d\n",j);
 for(i = 0; i < j; i++)
     {
      s[i] = (char *)malloc(sizeof(char)*(sstr[i].sstrlen + 1));
      strncpy(s[i], str + sstr[i].start, sstr[i].sstrlen);
      s[i][sstr[i].sstrlen] = '\0';
     }

 if(nsubs != (unsigned short *)0) *nsubs = (unsigned short)j;
 free(sstr);

 return s;
}
